import os
import subprocess

# A utility class to wrap the gnuplot functionality.
class GnuPlot:

  def __init__(self, template_file='./plot.plt.template', tmp_dir='/tmp/'):
    self.template_str = open(template_file, 'r').read().strip()
    self.tmp_dir = tmp_dir

  def sort_and_overwrite(self, data_file):
    tmp_filename = '/tmp/' + os.path.basename(data_file) + '.sorted'
    tmp_file = open(tmp_filename, 'w')
    subprocess.check_call(['sort', '-k', '1', '-n', data_file],
        stdout = tmp_file)
    tmp_file.close()
    subprocess.check_call(['mv', tmp_filename, data_file])

  def sort_data_series(self, data_series_map):
    for data_file in data_series_map.values():
      self.sort_and_overwrite(data_file)

  def plot(self, data_series_map, output_file, title):
    # Sort the data_series
    self.sort_data_series(data_series_map)

    # Prepare the plot commands.
    plot_commands = []
    for name, data_series_file in data_series_map.iteritems():
      cmd = "'%s' using 1:2 title '%s' with linespoints" % (
          data_series_file, name)
      plot_commands.append(cmd) 

    # The actual plot command.
    plot_command = 'plot ' + ','.join(plot_commands)

    # Create the plot script for gnu plot
    title_cmd = "set title '%s'" % title
    png_out_cmd = "set output '%s'" % output_file
    plot_file_str = '%s\n%s\n%s\n%s' % (
        self.template_str, title_cmd, png_out_cmd, plot_command)
    
    # Final plot script
    tmp_filename = self.tmp_dir + 'plot.tmp.plt'
    tmp_file = open(tmp_filename, 'w')
    tmp_file.write(plot_file_str)
    tmp_file.close()

    tmp_file = open(tmp_filename, 'r')
    subprocess.check_call(['gnuplot'], stdin=tmp_file) 
    tmp_file.close()
